<template>
	<view>
		<view class="content">
			<view class="btn_box">
				<button class="btn" open-type="getUserInfo" @getuserinfo="getUserInfo">登录</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				code: ''
			}
		},
		methods: {
			getUserInfo() {
				uni.showModal({
					title: "使用微信一键登录",
					showCancel: true,
					cancelColor: "#000000",
					confirmColor: "#42b983",
					success: (success) => {
						if (success.confirm) {
							uni.showLoading({
								title: '登录中...'
							})
							uni.getUserProfile({
								desc: '获取用户信息，进行登录',
								success: (res) => {
									//调用登录函数
									this.getLogin(res.userInfo)
								}
							})
						}
						if (success.cancel) {
							uni.showToast({
								title: '用户取消登录!',
								icon: 'none',
								duration: 2000
							});
						}
					}
				})
			},
			// 微信登录
			getLogin(userInfo) {
				uni.login({
					provider: 'weixin',
					success: (res) => {
						// 调用云函数
						uniCloud.callFunction({
							name: 'wxLogin', // 云函数名称
							data: { // 需要传递给云函数的参数
								userinfo: userInfo,
								code: res.code
							}
						}).then(ress => {
							console.log(ress);
							//判断是否返回了用户数据
							if (ress.result.affectedDocs != 0) {
								//存储用户信息
								this.UpdaUserInfo(ress.result.data[0])
								// 存储token
								uni.setStorage({
									key: 'Token',
									data: ress.result.data[0].token
								})
								uni.showToast({
									title: '登录成功',
									icon: 'none',
									duration: 2000
								});
								setTimeout(() => {
									// 跳转首页
									uni.reLaunch({
										url: '/pages/orderList/orderList'
									})
								}, 2000)
							} else {
								uni.showToast({
									title: '登录失败',
									icon: 'none',
									duration: 2000
								});
							}
							uni.hideLoading()


						}).catch(err => {
							console.log(err);
							uni.showToast({
								title: '登录失败',
								icon: 'none',
								duration: 2000
							});
						})
					}
				})
			},
			UpdaUserInfo(obj) {
				uni.setStorageSync('userObj', obj)
			}
			// getPhoneNumber(e) {
			// 	if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
			// 		// 如果拒绝授权登录，就走这里
			// 	} else {
			// 		console.log("phoneCode==>": e.detail.code)
			// 	}
			// }
		},
		onShow() {
			let token = uni.getStorageSync('Token')
			if (token) uni.navigateTo({
				url: '/pages/orderList/orderList'
			})
		},
		onLoad() {
			uni.hideTabBar()
		}
	}
</script>

<style>

</style>